using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySQL_SysFrameMVC.Message;
using System.Reflection;
using SysFrame.Message;
using SysFrame.BP;
using Newtonsoft.Json.Linq;
using TaskAPP.Message;
using System.Data;
using AssetFrame.Message;
using AssetFrame.BP;
using System.ComponentModel;

namespace TaskApp.BP
{
    /// <summary>
    /// taskapp_main方法
    /// </summary>
    public class BLLtaskapp_main
    {
        public Itaskapp_main interface_taskapp_main;

        public BLLtaskapp_main()
        {
            object obj = BPBase.GetAchieve("TaskApp.BP", "taskapp_main");
            interface_taskapp_main = (Itaskapp_main)obj;
        }


        /// <summary>
        /// 得到taskapp_main实体
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public List<Mstaskapp_main> Gettaskapp_mainMsByQuery(MsQuery msq)
        {
            return interface_taskapp_main.Gettaskapp_mainMsByQuery(msq);
        }

        public static T GetTaskMainMsg<T>(JObject data)
        {
            BLLtaskapp_main t = new BLLtaskapp_main();
            //T ms = (T)msobj;
            T ms = (T)data.ToObject(typeof(T));
            PropertyInfo[] propertys = ms.GetType().GetProperties();
            var p = propertys.First(m => m.Name == "TASKAPP_MAIN_AUTOID");
            string autoid = p.GetValue(ms).ToString();
            Mstaskapp_main mstask = t.Gettaskapp_mainMsByKey(autoid);

            for (int i = 0; i < propertys.Length; i++)
            {
                if (propertys[i].Name.IndexOf("TASKAPP_MAIN_") >= 0)
                {
                    try
                    {
                        propertys[i].SetValue(ms, propertys[i].GetValue(mstask, null));
                    }
                    catch (Exception ex) { }
                }
            }
            return ms;
        }

        /// <summary>
        /// 新增单据时 重置单据编号和时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tasktype"></param>
        /// <param name="ms"></param>
        /// <returns></returns>
        public void GetNewTask<T>(string tasktype, ref T ms)
        {
            Mstaskapp_main mstask = new Mstaskapp_main();
            mstask.TASKAPP_MAIN_10 = GetMaxSysCode(tasktype);
            mstask.TASKAPP_MAIN_MAKETIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            mstask.TASKAPP_MAIN_ISDEL = "0";
            try
            {
                mstask.TASKAPP_MAIN_MAKEUSER = Mssystem_1.GetLodeUser().System_1_10.ToString();
            }
            catch (Exception ex) { }
            mstask.TASKAPP_MAIN_20 = tasktype;
            mstask.TASKAPP_MAIN_60 = "011001";
            PropertyInfo[] propertys = ms.GetType().GetProperties();
            for (int i = 0; i < propertys.Length; i++)
            {
                if (propertys[i].Name.IndexOf("TASKAPP_MAIN_") >= 0)
                {
                    try
                    {
                        propertys[i].SetValue(ms, propertys[i].GetValue(mstask, null));
                    }
                    catch (Exception ex) { }
                }
            }
        }
        /// <summary>
        /// 日期加流水号 临时方法
        /// </summary>
        /// <returns></returns>
        public static string GetMaxSysCode(string tasktype)
        {
            MsQuery msq = new MsQuery();
            string date = DateTime.Now.ToString("yyyyMMdd");
            msq.strquery += " and TASKAPP_MAIN_MAKETIME like '" + DateTime.Now.ToString("yyyy-MM-dd") + "%'";
            DataTable dt = ((DataSet)(new BLLtaskapp_main().Gettaskapp_mainByQuery(msq).data)).Tables[0];
            return date + (dt.Rows.Count + 1).ToString().PadLeft(4, '0');
        }


        /// <summary>
        /// 通过TASKAPP_MAIN_AUTOID得到实体
        /// </summary>
        /// <param name="TASKAPP_MAIN_AUTOID">ID</param>
        /// <returns>实体</returns>
        public Mstaskapp_main Gettaskapp_mainMsByKey(string TASKAPP_MAIN_AUTOID)
        {
            MsQuery msquery = new MsQuery();
            msquery.strquery += " and TASKAPP_MAIN_AUTOID='" + TASKAPP_MAIN_AUTOID + "' ";
            List<Mstaskapp_main> lstData = Gettaskapp_mainMsByQuery(msquery);
            Mstaskapp_main ms = new Mstaskapp_main();
            ms = lstData[0];
            MsQuery listquery = new MsQuery();
            listquery.strquery += " and TASKAPP_MAINLIST_10 ='" + ms.TASKAPP_MAIN_AUTOID + "' and (TASKAPP_MAINLIST_ISDEL is null or TASKAPP_MAINLIST_ISDEL='0' or TASKAPP_MAINLIST_ISDEL='')";
            ms.TASKAPP_MAIN_list = new BLLtaskapp_mainlist().Gettaskapp_mainlistMsByQuery(listquery);
            return ms;
        }



        /// <summary>
        ///  保存taskapp_main信息
        /// </summary>
        /// <param name="ms">实体信息</param>
        /// <returns>消息</returns>
        public MsReturned Savetaskapp_main(Mstaskapp_main ms)
        {
            MsReturned msr = interface_taskapp_main.Savetaskapp_main(ms);
            BLLtaskapp_mainlist bllist = new BLLtaskapp_mainlist();
            /*对于主单明细 更细就是新增和删除，没有修改 
             * 先删除不在ID集合中的 not in
             * 再新增多出的
             */
            MsQuery msqdelete = new MsQuery();
            List<int> ids = new List<int>();
            try
            {
                ids = ms.assetids;
            }
            catch (Exception ex)
            { }
            if (ids == null)
            {
                ids = new List<int>();
            }
            ids.Add(-1);
            msqdelete.strquery += " and TASKAPP_MAINLIST_20 not in (" + string.Join(",", ids) + ")";
            msqdelete.strquery += " and TASKAPP_MAINLIST_10 = " + ms.TASKAPP_MAIN_AUTOID + "";
            bllist.Deletetaskapp_mainlistByQuery(msqdelete);

            MsQuery msqselect = new MsQuery();
            msqselect.strquery += " and TASKAPP_MAINLIST_20 in (" + string.Join(",", ids) + ")";
            msqselect.strquery += " and TASKAPP_MAINLIST_10 = " + ms.TASKAPP_MAIN_AUTOID + "";
            List<Mstaskapp_mainlist> mslist = bllist.Gettaskapp_mainlistMsByQuery(msqselect);
            //ids.Remove(-1);
            foreach (var item in ids)
            {
                int index = mslist.FindIndex(m => m.TASKAPP_MAINLIST_20 == item);
                if (item != -1 && index < 0)
                {
                    Mstaskapp_mainlist m = new Mstaskapp_mainlist();
                    m.TASKAPP_MAINLIST_10 = ms.TASKAPP_MAIN_AUTOID;
                    m.TASKAPP_MAINLIST_20 = item;
                    bllist.Savetaskapp_mainlist(m);

                }
            }

            return msr;
        }

        /// <summary>
        /// 通过单别得到查询资产的条件
        /// </summary>
        /// <param name="tasktype">单据类别</param>
        /// <returns></returns>
        public string GetTaskAssetQueryByTasktype(string tasktype)
        {
            /*没建表先返回固定值*/
            string wherestr = "";
            switch (tasktype)
            {
                case "010001": //调拨单
                    wherestr += " and a1.ASSET_A1_100 ='$$TASKAPP_C1_10$$'";
                    break;
                default:
                    break;
            }
            return wherestr;
        }

        /// <summary>
        /// 单据实例需要实现 单据验证委托
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public delegate MsReturned valiTask(string id);
        /// <summary>
        /// 事件实例
        /// </summary>
        public event valiTask valiT;

        /// <summary>
        /// 单据完成
        /// </summary>
        /// <param name="id">完成的ID</param>
        public void taskdone(string id)
        {
            Mstaskapp_main msmain = Gettaskapp_mainMsByKey(id);
            msmain.TASKAPP_MAIN_60 = "011002";
            Savetaskapp_main(msmain);
        }

        /// <summary>
        /// 根据单别配置 更新资产表
        /// </summary>
        /// <param name="tasktype">单据类别</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public MsReturned ChangAsset(string tasktype, JObject data)
        {
            JObject update = GetAssetUp(tasktype);
            MsReturned msr = new MsReturned();
            if (data["assetids"] != null)
            {
                List<int> assetids = new List<int>();
                List<Mstaskapp_mainlist> mainlist = new List<Mstaskapp_mainlist>();
                try
                {
                    assetids = (List<int>)data["assetids"].ToObject(typeof(List<int>));
                    mainlist = (List<Mstaskapp_mainlist>)data["TASKAPP_MAIN_list"].ToObject(typeof(List<Mstaskapp_mainlist>)); 
                }
                catch (Exception ex) { }
                Msasset_a1 msa1 = new Msasset_a1();
                BLLasset_a1 blla1 = new BLLasset_a1();
                foreach (Mstaskapp_mainlist list in mainlist)
                {
                    msa1 = new Msasset_a1();
                    msa1 = blla1.Getasset_a1MsByKey(list.TASKAPP_MAINLIST_20.ToString());
                    PropertyInfo[] propertys = msa1.GetType().GetProperties();
                    foreach (var item in update)
                    {
                        try
                        {
                            var p = propertys.First(m => m.Name == item.Key.ToString());
                            var value = item.Value;
                            if (!string.IsNullOrEmpty(value.ToString()))
                            {
                                if (value.ToString().IndexOf("$$") == 0)
                                {
                                    //需要得到 key的值 无限循环查找
                                    value = data[value.ToString().Replace("$$", "")];
                                }
                                p.SetValue(msa1, Convert.ChangeType(value, p.PropertyType), null);
                               
                            }
                        }
                        catch(Exception ex) { }
                    }
                    //for (int i = 0; i < propertys.Length; i++)
                    //{
                    //    if (update[propertys[i].Name] != null && !string.IsNullOrEmpty(update[propertys[i].Name].ToString()))
                    //    {
                    //        propertys[i].SetValue(msa1, update[propertys[i].Name]);
                    //    }
                    //}
                    blla1.Saveasset_a1(msa1);
                }

            }
            return msr;
        }

        /// <summary>
        /// 得到配置
        /// </summary>
        /// <param name="tasktype">单别</param>
        /// <returns></returns>
        private JObject GetAssetUp(string tasktype)
        {
            JObject update = new JObject();
            //该数据存在数据配置表 目前写死
            // 符号 $$ 表示动态数据 
            switch (tasktype)
            {
                case "010001"://调拨单
                    update.Add("ASSET_A1_100", "$$TASKAPP_C1_20$$");
                    break;
                default:
                    break;
            }
            return update;
        }

        /// <summary>
        /// 验证单据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tasktype"></param>
        /// <returns></returns>
        public MsReturned valiTaskMain(string id, string tasktype)
        {
            MsReturned msr = new MsReturned();
            Mstaskapp_main msmain = Gettaskapp_mainMsByKey(id);
            if (msmain.TASKAPP_MAIN_60 == "011002")
            {
                msr.strMsId = "-1";
                msr.strMS = "单据已经完成";
            }
            else
            {
                switch (tasktype)
                {
                    case "010001"://调拨单
                        BLLtaskapp_c1 bllc1 = new BLLtaskapp_c1(this);
                        msr = valiT(id);
                        break;
                    default:
                        break;
                }
            }
            return msr;
        }

        /// <summary>
        /// 得到数据类型
        /// </summary>
        /// <param name="msquery">条件</param>
        /// <returns>数据类型</returns>
        public MsReturned Gettaskapp_mainByQuery(MsQuery msquery)
        {
            return interface_taskapp_main.Gettaskapp_mainByQuery(msquery);
        }

        /// <summary>
        /// 删除taskapp_main
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public MsReturned Deletetaskapp_mainByQuery(MsQuery msq)
        {
            //默认逻辑删除 如果分类码为sysdel 则物理删除
            if (msq.typecode1 == "sysdel")
            {
                return interface_taskapp_main.Deletetaskapp_mainByQuery(msq);
            }
            else
            {
                List<Mstaskapp_main> listms = Gettaskapp_mainMsByQuery(msq);
                foreach (var item in listms)
                {
                    item.TASKAPP_MAIN_ISDEL = "1";
                    Savetaskapp_main(item);
                }
                MsReturned msr = new MsReturned();
                msr.strMsId = "1";
                msr.strMS = "保存成功!";
                return msr;
            }
        }
        /// <summary>
        /// 删除taskapp_main
        /// </summary>
        /// <param name="msq">条件</param>
        /// <returns></returns>
        public MsReturned Deletetaskapp_mainByKey(string TASKAPP_MAIN_AUTOID)
        {
            MsQuery msquery = new MsQuery();

            if (TASKAPP_MAIN_AUTOID.IndexOf(",") > 0)
            {
                msquery.strquery += " and TASKAPP_MAIN_AUTOID in (" + TASKAPP_MAIN_AUTOID + ") ";
            }
            else
            {
                msquery.strquery += " and TASKAPP_MAIN_AUTOID='" + TASKAPP_MAIN_AUTOID + "' ";
            }
            return interface_taskapp_main.Deletetaskapp_mainByQuery(msquery);
        }
    }
}
